#!/bin/bash

red='\033[0;31m'
green='\033[0;32m'
blue='\033[0;34m'
yellow='\033[0;33m'
plain='\033[0m'

cur_dir=$(pwd)

# 检查 root 权限
[[ $EUID -ne 0 ]] && echo -e "${red}错误：${plain} 请使用 root 权限运行此脚本 \n " && exit 1

# 检查操作系统并设置 release 变量
if [[ -f /etc/os-release ]]; then
    source /etc/os-release
    release=$ID
elif [[ -f /usr/lib/os-release ]]; then
    source /usr/lib/os-release
    release=$ID
else
    echo "无法检测系统版本，请联系作者！" >&2
    exit 1
fi
echo "当前系统版本：$release"

# 检测 CPU 架构
arch() {
    case "$(uname -m)" in
    x86_64 | x64 | amd64) echo 'amd64' ;;
    i*86 | x86) echo '386' ;;
    armv8* | armv8 | arm64 | aarch64) echo 'arm64' ;;
    armv7* | armv7 | arm) echo 'armv7' ;;
    armv6* | armv6) echo 'armv6' ;;
    armv5* | armv5) echo 'armv5' ;;
    s390x) echo 's390x' ;;
    *) echo -e "${green}不支持的 CPU 架构！${plain}" && rm -f install.sh && exit 1 ;;
    esac
}

echo "CPU 架构：$(arch)"

# 安装基础依赖
install_base() {
    case "${release}" in
    ubuntu | debian | armbian)
        apt-get update && apt-get install -y -q wget curl tar tzdata
        ;;
    centos | rhel | almalinux | rocky | ol)
        yum -y update && yum install -y -q wget curl tar tzdata
        ;;
    fedora | amzn | virtuozzo)
        dnf -y update && dnf install -y -q wget curl tar tzdata
        ;;
    arch | manjaro | parch)
        pacman -Syu && pacman -Syu --noconfirm wget curl tar tzdata
        ;;
    opensuse-tumbleweed)
        zypper refresh && zypper -q install -y wget curl tar timezone
        ;;
    *)
        apt-get update && apt-get install -y -q wget curl tar tzdata
        ;;
    esac
}

# 生成随机字符串
gen_random_string() {
    local length="$1"
    local random_string=$(LC_ALL=C tr -dc 'a-zA-Z0-9' </dev/urandom | fold -w "$length" | head -n 1)
    echo "$random_string"
}

# 安装后配置
config_after_install() {
    local existing_hasDefaultCredential=$(/usr/local/x-ui/x-ui setting -show true | grep -Eo 'hasDefaultCredential: .+' | awk '{print $2}')
    local existing_webBasePath=$(/usr/local/x-ui/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}')
    local existing_port=$(/usr/local/x-ui/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
    local URL_lists=(
        "https://api4.ipify.org"
		"https://ipv4.icanhazip.com"
		"https://v4.api.ipinfo.io/ip"
		"https://ipv4.myexternalip.com/raw"
		"https://4.ident.me"
		"https://check-host.net/ip"
    )
    local server_ip=""
    for ip_address in "${URL_lists[@]}"; do
        server_ip=$(curl -s --max-time 3 "${ip_address}" 2>/dev/null | tr -d '[:space:]')
        if [[ -n "${server_ip}" ]]; then
            break
        fi
    done

    if [[ ${#existing_webBasePath} -lt 4 ]]; then
        if [[ "$existing_hasDefaultCredential" == "true" ]]; then
            local config_webBasePath=$(gen_random_string 18)
            local config_username=$(gen_random_string 10)
            local config_password=$(gen_random_string 10)

            read -rp "是否自定义面板端口？（不自定义则使用随机端口）[y/n]：" config_confirm
            if [[ "${config_confirm}" == "y" || "${config_confirm}" == "Y" ]]; then
                read -rp "请设置面板端口：" config_port
                echo -e "${yellow}你的面板端口：${config_port}${plain}"
            else
                local config_port=$(shuf -i 1024-62000 -n 1)
                echo -e "${yellow}生成随机端口：${config_port}${plain}"
            fi

            /usr/local/x-ui/x-ui setting -username "${config_username}" -password "${config_password}" -port "${config_port}" -webBasePath "${config_webBasePath}"
            echo -e "首次安装，为安全生成随机登录信息："
            echo -e "###############################################"
            echo -e "${green}用户名：${config_username}${plain}"
            echo -e "${green}密码：${config_password}${plain}"
            echo -e "${green}端口：${config_port}${plain}"
            echo -e "${green}Web路径：${config_webBasePath}${plain}"
            echo -e "${green}访问地址：http://${server_ip}:${config_port}/${config_webBasePath}${plain}"
            echo -e "###############################################"
        else
            local config_webBasePath=$(gen_random_string 18)
            echo -e "${yellow}Web路径缺失或过短，生成新路径...${plain}"
            /usr/local/x-ui/x-ui setting -webBasePath "${config_webBasePath}"
            echo -e "${green}新Web路径：${config_webBasePath}${plain}"
            echo -e "${green}访问地址：http://${server_ip}:${existing_port}/${config_webBasePath}${plain}"
        fi
    else
        if [[ "$existing_hasDefaultCredential" == "true" ]]; then
            local config_username=$(gen_random_string 10)
            local config_password=$(gen_random_string 10)

            echo -e "${yellow}检测到默认凭证，需更新安全配置...${plain}"
            /usr/local/x-ui/x-ui setting -username "${config_username}" -password "${config_password}"
            echo -e "生成新随机登录凭证："
            echo -e "###############################################"
            echo -e "${green}用户名：${config_username}${plain}"
            echo -e "${green}密码：${config_password}${plain}"
            echo -e "###############################################"
        else
            echo -e "${green}用户名、密码、Web路径已正常配置，退出设置...${plain}"
        fi
    fi

    /usr/local/x-ui/x-ui migrate
}

# 安装 x-ui 核心逻辑
install_x-ui() {
    cd /usr/local/

    # 下载资源（关键修改：使用 Gitee 新地址）
    local arch_type=$(arch)
    # 仅支持 amd64 架构（根据提供的下载链接，当前仅提供 amd64 包）
    if [[ "${arch_type}" != "amd64" ]]; then
        echo -e "${red}当前仅支持 amd64 架构，你的架构 ${arch_type} 不兼容！${plain}"
        exit 1
    fi

    # 下载 x-ui 主程序包（新地址）
    local xui_package_url="https://foruda.gitee.com/attach_file/1758176454820123042/x-ui-linux-amd64.tar.gz?token=9380eb8d718d38c350f2f8c8c56c3664&ts=1758186637&attname=x-ui-linux-amd64.tar.gz"
    echo -e "开始下载 x-ui 程序包（amd64 架构）..."
    wget -N -O /usr/local/x-ui-linux-${arch_type}.tar.gz "${xui_package_url}"
    if [[ $? -ne 0 ]]; then
        echo -e "${red}下载 x-ui 程序包失败，请检查网络或链接有效性${plain}"
        exit 1
    fi

    # 下载 x-ui 命令行脚本（新地址）
    local xui_cli_url="https://gitee.com/sou9602/3x-ui/raw/main/x-ui.sh"
    echo -e "开始下载 x-ui 命令行脚本..."
    wget -O /usr/bin/x-ui-temp "${xui_cli_url}"
    if [[ $? -ne 0 ]]; then
        echo -e "${red}下载 x-ui 命令行脚本失败，请检查网络或链接有效性${plain}"
        rm -f /usr/local/x-ui-linux-${arch_type}.tar.gz  # 清理已下载的包
        exit 1
    fi

    # 停止旧服务并清理残留
    if [[ -e /usr/local/x-ui/ ]]; then
        systemctl stop x-ui
        rm /usr/local/x-ui/ -rf
    fi

    # 解压并设置权限
    tar zxvf x-ui-linux-${arch_type}.tar.gz
    rm x-ui-linux-${arch_type}.tar.gz -f
    
    cd x-ui
    chmod +x x-ui
    chmod +x x-ui.sh

    # 架构适配（仅处理 arm 系列，amd64 跳过）
    if [[ "${arch_type}" == "armv5" || "${arch_type}" == "armv6" || "${arch_type}" == "armv7" ]]; then
        mv bin/xray-linux-${arch_type} bin/xray-linux-arm
        chmod +x bin/xray-linux-arm
    fi
    chmod +x x-ui bin/xray-linux-${arch_type}

    # 更新命令行脚本并授权
    mv -f /usr/bin/x-ui-temp /usr/bin/x-ui
    chmod +x /usr/bin/x-ui

    # 执行安装后配置
    config_after_install

    # 配置系统服务并启动
    cp -f x-ui.service /etc/systemd/system/
    systemctl daemon-reload
    systemctl enable x-ui
    systemctl start x-ui

    echo -e "${green}x-ui 安装完成，已启动服务...${plain}"
    echo -e ""
    echo -e "┌───────────────────────────────────────────────────────┐
│  ${blue}x-ui 管理命令说明：${plain}                                  │
│                                                       │
│  ${blue}x-ui${plain}              - 打开管理菜单                    │
│  ${blue}x-ui start${plain}        - 启动服务                      │
│  ${blue}x-ui stop${plain}         - 停止服务                      │
│  ${blue}x-ui restart${plain}      - 重启服务                      │
│  ${blue}x-ui status${plain}       - 查看服务状态                  │
│  ${blue}x-ui settings${plain}     - 查看配置信息                  │
│  ${blue}x-ui enable${plain}       - 设置开机自启                  │
│  ${blue}x-ui disable${plain}      - 取消开机自启                  │
│  ${blue}x-ui log${plain}          - 查看运行日志                  │
│  ${blue}x-ui banlog${plain}       - 查看封禁日志                  │
│  ${blue}x-ui update${plain}       - 升级程序                      │
│  ${blue}x-ui legacy${plain}       - 切换旧版本                    │
│  ${blue}x-ui install${plain}      - 重新安装                    │
│  ${blue}x-ui uninstall${plain}    - 卸载程序                      │
└───────────────────────────────────────────────────────┘"
}

echo -e "${green}开始执行 x-ui 安装流程...${plain}"
install_base
install_x-ui $1